package com.cc.springbootvalidatedemo.utils;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.regex.Pattern;

public class PhoneValidator implements ConstraintValidator<ValidPhone, String> {

    private static final Pattern PATTERN = Pattern.compile("^1\\d{10}$");

    private int code;

    @Override
    public void initialize(ValidPhone constraintAnnotation) {
        code = constraintAnnotation.code();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        boolean isValid = value == null || PATTERN.matcher(value).matches();
        if (!isValid) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                    .addPropertyNode(String.valueOf(code))
                    .addConstraintViolation();
            // 或者使用其他方式传递错误码
        }
        return isValid;
    }
}
